import { addApiApi, delApiApi, editApiApi } from '@/api/system/sysapi/api'
import { ApiModel, ApiParam, RequestMethod } from '@/api/system/sysapi/ApiModel'
import useInstance from '@/hooks/useInstance'
import { Result, StatusCode } from '@/http/request'
import { EditType } from '@/types/BaseEnum'
import { onMounted, reactive, ref } from 'vue'

export default function useApi(getApiList: any) {
    const { global } = useInstance()

    // 新增弹框ref属性
    const addEditRef = ref<{
        show: (type: string, row?: ApiModel) => void
    }>()
    // const addDeptRef = ref<InstanceType<typeof AddAndEdit>>() // 打包时会报错

    const methodData = reactive({
        data: Array<RequestMethod>()
    })

    const addModel = reactive<ApiModel>({
        id: '',
        type: EditType.ADD,
        parent_id: '',
        description: '',
        path: '',
        method: ''
    })

    // 新增
    const addBtn = (parent_id: string) => {
        addModel.parent_id = parent_id
        addEditRef.value?.show(EditType.ADD, addModel)
    }

    // 编辑
    const editBtn = async (row: ApiModel) => {
        addEditRef.value?.show(EditType.EDIT, row)
    }

    // 删除
    const delBtn = async (id: number) => {
        console.log(global)
        const confirm = await global.$eleConfirm('确定删除该数据吗？')
        if (confirm) {
            // 执行删除操作
            const param = reactive<ApiParam>({
                id: id
            })
            let res = await delApiApi(param)
            if (res && res.code == StatusCode.Success) {
                // 刷新列表
                getApiList()
                // 信息提示
                global.$message({ message: res.msg, type: 'success' })
            }
        }
    }

    // 保存
    const save = async (param: ApiModel) => {
        console.log('保存：', param)
        let res: Result
        if (param.type == EditType.ADD) {
            res = await addApiApi(param)
        } else {
            res = await editApiApi(param)
        }
        if (res && res.code == StatusCode.Success) {
            // 信息提示
            global.$message({ message: res.msg, type: 'success' })
            // 刷新表格
            getApiList()
        }
    }

    // 首次加载
    onMounted(() => {
        methodData.data = [
            {
                value: 'GET',
                label: '查看(GET)'
            },
            {
                value: 'POST',
                label: '创建(POST)'
            },
            {
                value: 'PUT',
                label: '更新(PUT)'
            },
            {
                value: 'DELETE',
                label: '删除(DELETE)'
            }
        ]
    })

    return {
        addBtn,
        editBtn,
        delBtn,
        save,
        addEditRef,
        methodData
    }
}
